//###############
//FILE : ConnectionManager.java
//WRITER : Daniel Lowengrub, daniel_i_l, 320687098
//EXERCISE : oop ex3 2011
//DESCRIPTION:
//See below
//###############

package oop.ex3.communication;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;

/**
 * This class opens a socket on a given port and creates input and output streams.
 * It takes care of opening the streams and closing them after use.
 * @author daniel
 */
public class ConnectionManager {
    private Socket _socket;
    private DataInputStream _inputStream;
    private DataOutputStream _outputStream;

    /**
     * Create a socket on the given address and initialize input/output streams.
     * @param addr The address the socket should listen to.
     * @return True if the streams were created and False in case of failure.
     */
    public boolean initializeStreams(SocketAddress addr) {
        try {
            _socket = Communication.getSocket(addr);
            _inputStream = Communication.getInputStreamFromSocket(_socket);
            _outputStream = Communication.getOutputStreamFromSocket(_socket);
        } catch (Exception ex) {
            return false;
        }

        return true;
    }

    /**
     * Get the created input stream. This only works after initializeStreams
     * has been called successfully.
     * @return the input stream.
     */
    public DataInputStream getInputStream() {
        return _inputStream;
    }

    /**
     * Get the created output stream. This only works after initializeStreams
     * has been called successfully.
     * @return the output stream.
     */
    public DataOutputStream getOutputStream() {
        return _outputStream;
    }

    /**
     * Close the sockets and streams that were created in the initializeStreams call.
     */
    public void closeConnection() {
        try {
            _socket.close();
            _inputStream.close();
            _outputStream.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }


}
